<template>
  <view class="store">
    <up-alert
      v-if="merchantStatus == 'approve'"
      :title="form.name + '：审核中'"
      type="warning"
    ></up-alert>
    <up-alert
      v-else-if="merchantStatus == 'reject'"
      :title="form.name + '：审核被拒'"
      type="error"
    ></up-alert>
    <up-alert
      v-else-if="merchantStatus == 'locked'"
      :title="form.name + '：已锁定'"
      type="info"
    ></up-alert>

    <view class="card-box">
      <view class="form-item" v-if="!is_merchant">
        <view class="form-item-key">账号手机</view>
      </view>
      <view class="form-item">
        <view class="form-item-key"
          ><text class="rules" v-if="!is_merchant">*</text>联系人</view
        >
        <text v-if="is_merchant">{{ form.contact_name }}</text>
        <up-input
          v-else
          placeholder="请填写姓名"
          border="none"
          v-model="form.contact_name"
          inputAlign="right"
        ></up-input>
      </view>
      <view class="form-item">
        <view class="form-item-key"
          ><text class="rules" v-if="!is_merchant">*</text>联系电话</view
        >
        <text v-if="is_merchant">{{ form.contact_phone }}</text>
        <up-input
          v-else
          placeholder="请填写手机号码"
          border="none"
          v-model="form.contact_phone"
          inputAlign="right"
        ></up-input>
      </view>
    </view>
    <view class="card-box">
      <view class="form-item">
        <view class="form-item-key"
          ><text class="rules" v-if="!is_merchant">*</text>门店名称</view
        >
        <text v-if="is_merchant">{{ form.name }}</text>
        <up-input
          v-else
          placeholder="请填写门店名称，最多20字"
          maxlength="20"
          border="none"
          v-model="form.name"
          inputAlign="right"
        ></up-input>
      </view>
      <view class="form-item">
        <view class="form-item-key">
          <text class="rules" v-if="!is_merchant">*</text>门店类目
        </view>
        <view class="flex-1 flex" style="justify-content: flex-end">
          <text
            v-if="form.subjects.length"
            @click="toChooseSubject"
            style="color: #2ca544"
          >
            {{ subjectLabel }}
          </text>
          <text v-else @click="toChooseSubject">请选择类目</text>
        </view>
      </view>
      <view class="form-item">
        <view class="form-item-key">
          <text class="rules" v-if="!is_merchant">*</text>所在地区
        </view>

        <view class="city-select-btn" @click="onOpenPopup">
          <view v-if="form.province_id && form.city_id && form.district_id">
            <text v-for="(city, index) in selectCity" :key="city.id"
              >{{ city.name
              }}{{ index < selectCity.length - 1 ? "/" : "" }}</text
            >
          </view>
          <view v-else>请选择</view>
        </view>
      </view>

      <view class="store-location">
        <view class="location-top">
          <view><text class="rules" v-if="!is_merchant">*</text>门店地址</view>
          <view class="location-address" v-if="is_merchant">{{
            form.address
          }}</view>
          <view v-else class="location-btn" @click="chooseAddressView"
            >选择定位</view
          >
        </view>
        <view v-if="!is_merchant">
          <up-textarea v-model="form.address"></up-textarea>
        </view>
      </view>
      <view class="store-image">
        <view class="store-image-left"
          ><text class="rules" v-if="!is_merchant">*</text>门头照片</view
        >
        <view class="store-image-right">
          <u-upload
            v-if="!is_merchant"
            width="100"
            height="100"
            :maxCount="1"
            :fileList="files"
            @afterRead="afterRead"
            @beforeRead="beforeRead"
            @delete="deletePic"
            name="file"
            :multiple="true"
            :previewFullImage="true"
          ></u-upload>
          <image
            v-else
            style="width: 200rpx; height: 200rpx; border-radius: 10rpx"
            :src="form.store_image"
          >
          </image>
        </view>
      </view>
    </view>

    <view class="submit-box" v-if="!is_merchant">
      <up-button
        type="primary"
        shape="circle"
        text="确认提交"
        @click="onSubmit"
      ></up-button>
    </view>

    <up-popup :show="popupShow" mode="bottom" round="10">
      <view class="popup-mian">
        <view class="popup-top">
          <view class="popup-btn cancel-btn" @click="onClosePopup">取消</view>
          <view class="popup-title">选择所在地区</view>
          <view class="popup-btn confirm-btn" @click="onConfirmPopup">
            确认
          </view>
        </view>
        <view class="city-select">
          <view
            class="select-item"
            v-for="(row, index) in selectCity"
            :key="index"
            :class="{ active: cityActive == index }"
            @click="onCityLevel(index)"
          >
            {{ row.name }}
          </view>
        </view>
        <scroll-view scroll-y style="height: 500rpx">
          <view class="city-list">
            <view
              class="city-item flex justify-between"
              :class="{ active: item.id == selectCity[cityActive].id }"
              v-for="item in cityList"
              :key="item.id"
              @click="onCitySelect(item)"
            >
              <text>{{ item.name }}</text>
              <u-icon
                v-if="item.id == selectCity[cityActive].id"
                name="checkbox-mark"
                color="primary"
              ></u-icon>
            </view>
          </view>
        </scroll-view>
      </view>
    </up-popup>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from "vue";
import { apiConfigAddress, uploadFile } from "@/common/apis/common.js";
import { postMerchtants, merchtantsCurrent } from "@/common/apis/store.js";
import { useStore } from "vuex";
import { urlToObj } from "@/util/index.js";

const store = useStore();

const cityList = ref([]);
const selectCity = reactive([
  { id: 0, name: "选择省" },
  { id: 0, name: "选择市" },
  { id: 0, name: "选择区" },
]);
const popupShow = ref(false);
const cityActive = ref(0);
const merchantStatus = ref("");
const form = reactive({
  name: "",
  address: "",
  province_id: 0,
  city_id: 0,
  district_id: 0,
  referrer_id: 0,
  longitude: 0,
  latitude: 0,
  contact_name: "",
  contact_phone: "",
  store_image: "",
  subjects: [],
});
const is_merchant = ref(false);
const longitude = ref(0);
const latitude = ref(0);
const files = ref([]);
const subjectLabel = ref("");

const options = uni.getEnterOptionsSync();
if (options.query.scene) {
  const query = urlToObj(decodeURIComponent(options.query.scene));
  if (query.agent) {
    form.agent = query.agent;
  }
}

async function getConfigAddressData(parent_id) {
  const response = await apiConfigAddress({ parent_id });
  if (response) {
    cityList.value = response;
  }
}

function onOpenPopup() {
  if (is_merchant.value) return;
  getConfigAddressData();
  popupShow.value = true;
}

function onCityLevel(index) {
  if (index == 0) {
    cityActive.value = 0;
    selectCity[1] = { id: "", name: "选择市" };
    selectCity[2] = { id: "", name: "选择区" };
    getConfigAddressData();
  } else if (index == 1 && selectCity[index].id) {
    cityActive.value = 1;
    selectCity[2] = { id: "", name: "选择区" };
    getConfigAddressData(selectCity[0].id);
  }
}

function onCitySelect(row) {
  selectCity[cityActive.value] = JSON.parse(JSON.stringify(row));
  if (cityActive.value < 2) {
    cityActive.value++;
    getConfigAddressData(row.id);
  }
}

function onClosePopup() {
  popupShow.value = false;
}

function onConfirmPopup() {
  form.province_id = selectCity[0].id || 0;
  form.city_id = selectCity[1].id || 0;
  form.district_id = selectCity[2].id || 0;
  if (!form.province_id) {
    return uni.showToast({
      title: "请选择省份",
      icon: "none",
    });
  } else if (!form.city_id) {
    return uni.showToast({
      title: "请选择市",
      icon: "none",
    });
  } else if (!form.district_id) {
    return uni.showToast({
      title: "请选择区",
      icon: "none",
    });
  }
  popupShow.value = false;
}

//获取当前的地理位置
function getLocation() {
  uni.showLoading({
    title: "正在获取定位中...",
  });
  uni.getLocation({
    type: "gcj02",
    isHighAccuracy: true,
    geocode: "true",
    highAccuracyExpireTime: 3500,
    success: (res) => {
      uni.hideLoading();
      longitude.value = res.longitude;
      latitude.value = res.latitude;
    },
    fail: (res) => {
      console.log("error=", res);
      if (res.errMsg == "getLocation:fail auth deny") {
        uni.showModal({
          content: "检测到您没打开获取信息功能权限，是否去设置打开？",
          confirmText: "确认",
          cancelText: "取消",
          success: (res) => {
            if (res.confirm) {
              uni.openSetting({
                success: (res) => {},
              });
            } else {
              return false;
            }
          },
        });
      }
    },
  });
}

//选择地址
function chooseAddressView() {
  uni.chooseLocation({
    success: (res) => {
      if (!res.name || !res.address || !res.latitude || !res.longitude) return;
      form.latitude = res.latitude;
      form.longitude = res.longitude;
      form.address = res.address + res.name;
      latitude.value = res.latitude;
      longitude.value = res.longitude;
      console.log(res);
    },
  });
}

// 删除图片
function deletePic(event) {
  files.value.splice(event.index, 1);
  form.store_image = "";
}
function beforeRead(event) {
  console.log(event);
}
// 新增图片
async function afterRead(event) {
  // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
  let lists = [].concat(event.file);
  let fileListLen = files.value.length;
  lists.map((item) => {
    files.value.push({
      ...item,
      status: "uploading",
      message: "上传中",
    });
  });
  for (let i = 0; i < lists.length; i++) {
    const result = await uploadFile(lists[i].url);
    let item = files.value[fileListLen];
    files.value.splice(
      fileListLen,
      1,
      Object.assign(item, {
        status: "success",
        message: "",
        url: result.url,
      })
    );
    form.store_image = result.url;
    fileListLen++;
  }
}

async function getMerchtantsCurrent() {
  const respone = await merchtantsCurrent();
  if (respone && respone.data && respone.data.info) {
    is_merchant.value = respone.data.is_merchant;
    const merchant = respone.data.info;
    merchantStatus.value = merchant.status || "";
    form.name = merchant.name;
    form.address = merchant.address;
    form.province_id = merchant.province.id;
    form.city_id = merchant.city.id;
    form.district_id = merchant.district.id;
    form.referrer_id = 0;
    form.longitude = merchant.longitude;
    form.latitude = merchant.latitude;
    form.contact_name = merchant.contact_name;
    form.contact_phone = merchant.contact_phone;
    form.store_image = merchant.store_image;
    form.subjects = merchant.subjects.map((i) => i.id);
    subjectLabel.value = merchant.subjects.map((i) => i.name).join("、");
    selectCity[0] = JSON.parse(JSON.stringify(merchant.province));
    selectCity[1] = JSON.parse(JSON.stringify(merchant.city));
    selectCity[2] = JSON.parse(JSON.stringify(merchant.district));
    uni.setNavigationBarTitle({
      title: "商户信息",
    });
  } else {
    // getLocation();
  }
}

let isSubmit = false;
async function onSubmit() {
  if (!form.contact_name) {
    return uni.showToast({
      title: "请输入联系人",
      icon: "none",
    });
  }
  if (!form.contact_phone) {
    return uni.showToast({
      title: "请输入联系电话",
      icon: "none",
    });
  }
  if (!form.name) {
    return uni.showToast({
      title: "请输入门店名称",
      icon: "none",
    });
  }
  if (!form.subjects.length) {
    return uni.showToast({
      title: "请选择门店类目",
      icon: "none",
    });
  }
  if (!form.province_id && !form.city_id && !form.district_id) {
    return uni.showToast({
      title: "请选择所在地区",
      icon: "none",
    });
  }
  if (!form.address) {
    return uni.showToast({
      title: "请选择门店地址",
      icon: "none",
    });
  }
  if (!form.address) {
    return uni.showToast({
      title: "请选择门店地址",
      icon: "none",
    });
  }
  if (!form.store_image) {
    return uni.showToast({
      title: "请上传门头照片",
      icon: "none",
    });
  }
  if (isSubmit) return;
  isSubmit = true;
  uni.showLoading({ title: "提交中" });
  const respone = await postMerchtants(form);
  uni.hideLoading();
  if (respone) {
    uni.showToast({
      title: "提交成功",
      icon: "success",
    });
    getMerchtantsCurrent();
  }
  isSubmit = false;
  uni.hideLoading();
}

function toChooseSubject() {
  uni.$u.route({
    url: "/pages/app/choose-subject",
    params: {
      subjects: JSON.stringify(form.subjects),
    },
  });
}

/**
 * 对比两个数组的 id，找出多出来的 id 和减少的 id
 * @param {Array} oldArray - 旧数组
 * @param {Array} newArray - 新数组
 * @returns {Object} - 包含多出来的 id 和减少的 id 的对象
 */
function compareIds(oldArray, newArray) {
  const oldIds = new Set(oldArray);
  const newIds = new Set(newArray);

  const addedIds = [];
  const removedIds = [];

  // 找出多出来的 id
  newIds.forEach((id) => {
    if (!oldIds.has(id)) {
      addedIds.push(id);
    }
  });

  // 找出减少的 id
  oldIds.forEach((id) => {
    if (!newIds.has(id)) {
      removedIds.push(id);
    }
  });

  return {
    addedIds,
    removedIds,
  };
}

onMounted(async () => {
  uni.$on("chooseSubjects", (subjects, label) => {
    if (store.state.user.isStore) {
      const promises = [];
      const { addedIds, removedIds } = compareIds(form.subjects, subjects);
      addedIds.forEach((i) => {
        promises.push(store.dispatch("fetchAddMerchantSubject", i));
      });
      removedIds.forEach((i) => {
        promises.push(store.dispatch("fetchDelMerchantSubject", i));
      });
      uni.showLoading({ mask: true, title: "正在修改类目" });
      Promise.all(promises)
        .then(() => {
          form.subjects = subjects;
          subjectLabel.value = label;
          store.dispatch(
            "fetchMerchantSubjectList",
            store.state.user.storeInfo.id
          );
          uni.hideLoading();
        })
        .catch(() => {
          getMerchtantsCurrent();
          uni.hideLoading();
        });
    } else {
      form.subjects = subjects;
      subjectLabel.value = label;
    }
  });
  await getMerchtantsCurrent();
});

onUnmounted(() => {
  uni.$off("chooseSubjects");
});
</script>

<style lang="scss" scoped>
.store {
  .card-box {
    margin: 20rpx;
    padding: 0 20rpx;
    border-radius: 20rpx;
    background-color: #ffffff;

    .form-item {
      padding: 40rpx 0;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: 2rpx solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      .form-item-key {
        width: 160rpx;
      }

      .city-select-btn {
        flex: 1;
        padding: 10rpx 0;
        text-align: right;
      }
    }

    .store-location {
      padding-bottom: 20rpx;

      .location-top {
        height: 100rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .location-btn {
          color: #3cb9ef;
        }
        .location-address {
          width: 500rpx;
          text-align: right;
        }
      }

      .location-address {
        color: #333333;
        margin-top: 10rpx;
      }
    }

    .store-image {
      margin-bottom: 20rpx;

      .store-image-left {
        height: 80rpx;
        line-height: 80rpx;
      }
    }
  }

  .map-marker {
    height: 62rpx;
    position: absolute;
    top: 40%;
    left: 50%;
    transform: translate(-50%, -50%);
  }

  .submit-box {
    padding: 40rpx 40rpx calc(40rpx + env(safe-area-inset-bottom)) 40rpx;
  }

  .popup-mian {
    .popup-top {
      padding: 20rpx;
      background-color: #ffffff;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .popup-title {
        font-size: 30rpx;
        font-weight: bold;
      }

      .cancel-btn {
        color: #666666;
      }

      .confirm-btn {
        color: #3cb9ef;
      }
    }

    .city-select {
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: 2rpx solid #f0f0f0;

      .select-item {
        width: calc(100% / 3);
        padding: 20rpx;

        &.active {
          color: #3cb9ef;
        }
      }
    }

    .city-list {
      height: 500rpx;

      .city-item {
        height: 80rpx;
        border-bottom: 2rpx solid #f0f0f0;
        padding: 0 20rpx;
        line-height: 80rpx;
        &.active {
          color: $u-primary;
        }
      }
    }
  }

  .rules {
    color: #ff0000;
  }
}
</style>
